<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>科泰聊天室</title>
  <link href="css/chat.css" rel="stylesheet">
</head>

<body>
  <!-- 整个聊天应用可以看作一个父组件，其下包含聊天窗口、输入框等子组件 -->
  <div id="app">
    <h1 class="title center">科泰聊天室</h1>
    <div class="chat-window center">
      <!-- 聊天消息展示区域可看作一个子组件 -->
      <div class="chat-messages">
        <div class="message received-message">
          <div class="message-received"><img src="images/avt-01.png" class="avatar"> <span
              class="message-content">好久不见！</span></div>
        </div>
        <div class="message sent-message">
          <div class="message-sent"><span class="message-content">是啊，好久不见了</span> <img src="images/avt-02.png"
              class="avatar"></div>
        </div>
        <div class="message received-message">
          <div class="message-received"><img src="images/avt-01.png" class="avatar"> <span
              class="message-content">最近怎么样？</span></div>
        </div>
      </div>
      <!-- 聊天输入区域可看作一个子组件 -->
      <div class="chat-input">
        <input type="text" placeholder="请输入消息..." v-model="newMessage">
        <button @click.prevent="sendMessage">发送</button>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: {
        newMessage: ''
      },
      methods: {
        sendMessage() {
          if (this.newMessage.trim()!== '') {
            // 创建代表发送消息的DOM元素并添加到聊天记录显示区域
            const sentMessageDiv = document.createElement('div');
            sentMessageDiv.classList.add('message','sent-message');
            const messageSentDiv = document.createElement('div');
            messageSentDiv.classList.add('message-sent');
            const messageContentSpan = document.createElement('span');
            messageContentSpan.classList.add('message-content');
            messageContentSpan.textContent = this.newMessage;
            const avatarImg = document.createElement('img');
            avatarImg.src = "images/avt-02.png";
            avatarImg.classList.add('avatar');

            messageSentDiv.appendChild(messageContentSpan);
            messageSentDiv.appendChild(avatarImg);
            sentMessageDiv.appendChild(messageSentDiv);

            document.querySelector('.chat-messages').appendChild(sentMessageDiv);

            // 发送消息后清空输入框
            this.newMessage = '';
          }
        }
      }
    });
  </script>
</body>

</html>